<template>
  <Drawer
      v-model="visible"
      title="数据库编辑"
      width="490"
      :mask-closable="false"
      :styles="$PnUtil.buildDrawerStyleByHasFooter()">
    <Form ref="form" :label-width="100" :model="formData" :rules="ruleValidate">
      <FormItem label="备注名称" prop="alias_name">
        <Input v-model="formData.alias_name" placeholder="数据库的别名，可输入任意字符"/>
      </FormItem>
      <FormItem label="引用名" prop="pool_name">
        <i-input v-model="formData.pool_name" placeholder="唯一标识数据库引用，只能输入英文与数字">
          <Button slot="append" @click="checkPoolName">检查是否可用</Button>
        </i-input>
      </FormItem>
      <FormItem label="数据库类型" prop="driver_class_name">
        <Select :transfer="true" v-model="formData.driver_class_name">
          <Option v-for="item in dbTypes" :value="item.value" :key="item.value" :label="item.label">
            <span style="color: #2196f3;">{{ item.label }}</span>
            <p style="color: #ccc;">{{item.value}}</p>
          </Option>
        </Select>
      </FormItem>
      <FormItem label="URL地址" prop="url">
        <Input type="textarea" :rows="4" v-model="formData.url" placeholder=""/>
      </FormItem>
      <FormItem label="用户名" prop="username">
        <Input v-model="formData.username" placeholder=""/>
      </FormItem>
      <FormItem label="密码" prop="password">
        <Input type="password" v-model="formData.password" placeholder=""/>
      </FormItem>
      <FormItem>
        <Button type="default" size="small" :loading="testDatabaseConnLoading" @click="testDatabaseConn">测试连接</Button>
      </FormItem>
      <FormItem>
        <FormItemPanel title="温馨提示">
          <p>请确保数据库可以被公网访问，且开启了远程访问的权限</p>
          <p>请确保数据库没有被防火墙禁止</p>
          <p>请确保数据库域名能够被解析</p>
          <p>请确保数据库已经启动</p>
        </FormItemPanel>
      </FormItem>
    </Form>

    <DrawerFooter>
      <Button class="m-r-5px" @click="visible = false">关闭</Button>
      <Button type="primary" @click="submitForm" :loading="loading">保存</Button>
    </DrawerFooter>
  </Drawer>
</template>

<script>
import ManageMixin from "@/mixin/ManageMixin";

export default {
  name: 'DatabaseForm',
  mixins: [ManageMixin],
  data() {
    const validatePoolName = (rule, value, callback) => {
      let reg = /^[A-Za-z0-9]+$/g
      if (value === '') {
        callback(new Error('引用名不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('只能输入英文字母与数字'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      loading: false,
      testDatabaseConnLoading: false,
      dbTypes: [
        {
          label: 'MySql',
          value: 'com.mysql.cj.jdbc.Driver'
        },
        {
          label: 'Oracle',
          value: 'oracle.jdbc.driver.OracleDriver'
        },
        {
          label: 'PostgresqlSQL',
          value: 'org.postgresql.Driver'
        },
        {
          label: 'SQLServer',
          value: 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
        },
        {
          label: 'Sybase',
          value: 'net.sourceforge.jtds.jdbc.Driver'
        },
        {
          label: 'H2',
          value: 'org.h2.Driver'
        },
        {
          label: 'SQLite（测试）',
          value: 'org.sqlite.JDBC'
        },
        {
          label: '达梦数据库（测试）',
          value: 'dm.jdbc.driver.DmDriver'
        },
        {
          label: 'TDengine（测试）',
          value: 'com.taosdata.jdbc.rs.RestfulDriver'
        },
      ],
      formData: {
        id: '',
        alias_name: '',
        pool_name: '',
        driver_class_name: '',
        url: '',
        username: '',
        password: '',
        user_id: ''
      },
      ruleValidate: {
        alias_name: [
          {required: true, message: '备注名称不能为空', trigger: 'blur'}
        ],
        pool_name: [
          {required: true, validator: validatePoolName, trigger: 'blur'}
        ],
        driver_class_name: [
          {required: true, message: '驱动类名不能为空', trigger: 'blur'}
        ],
        url: [
          {required: true, message: 'URL不能为空', trigger: 'blur'}
        ],
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {

  },
  methods: {
    init(type, id) {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (type == 'edit') {

        }
      })
    },

    checkPoolName() {
      if (!this.formData.pool_name || new RegExp("^[ ]+$").test(this.formData.pool_name)) {
        this.$Message.warning('请输入引用名')
      }else {
        this.$PnApi.DatabaseApi.checkPoolName(this.formData.pool_name).then(result => {
          if (result.data.success) {
            this.$Message.success(result.data.message)
          }else {
            this.$Message.error(result.data.message)
          }
        })
      }
    },
    testDatabaseConn() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.testDatabaseConnLoading = true
          this.$PnApi.DatabaseApi.testDatabaseConn({
            driver_class_name: this.formData.driver_class_name,
            url: this.formData.url,
            username: this.formData.username,
            password: this.formData.password
          }).then(result => {
            if (result.data.success) {
              this.$Message.success(result.data.message)
            } else {
              this.$Message.error({
                content: result.data.message,
                duration: 8
              })
            }
            this.testDatabaseConnLoading = false
          })
        }
      });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$PnApi.DatabaseApi.addDatabase(this.formData).then(result => {
            if (result.data.success) {
              this.visible = false
              this.$Message.success(result.data.message)
              this.$emit("refreshDataList")
            }else {
              this.$Message.error({
                content: result.data.message,
                duration: 8
              })
            }
            this.loading = false
          })
        }
      });
    }
  },
  computed: {}
}
</script>

<style scoped>

</style>
